package br.edu.fa7.quotes.model;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import br.edu.fa7.quotes.R;
import br.edu.fa7.quotes.ui.Notificacao;

public class ServicoNotificar extends Service {

	private static final int TIMER = 600000;
	private NotificationManager notificationManager;
	private NotificationDeamon notificationDaemon;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificar();
		return super.onStartCommand(intent, flags, startId);
	}

	private void notificar() {
		if ( notificationDaemon == null ) {
			notificationDaemon = new NotificationDeamon();
			notificationDaemon.start();
		}
	}
	
	private class NotificationDeamon extends Thread {
		
		@Override
		public void run() {
			while ( !isInterrupted() ) {
				try {
					criarNotificacao();
					Thread.sleep(TIMER);
				} catch (InterruptedException e) {
					Log.e("NotificationSevice", "Notification Deamon was interrupted", e);
				}
			}
		}
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		notificationDaemon.interrupt();
		release();
	}

	private void release() {
		notificationDaemon = null;
		notificationManager = null;
	}

	protected void criarNotificacao() {
		 CharSequence warning = getString(R.string.notificationWarning);
		 CharSequence title = getString(R.string.notificationTitle);
		 CharSequence subtitle = getString(R.string.notificationSubtitle);
		
		
		final Notification notificacao = new Notification(R.drawable.ic_launcher, warning, System.currentTimeMillis());
		final PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, Notificacao.class), 0);
		notificacao.setLatestEventInfo(this, title, subtitle, intent);
		notificacao.vibrate = new long[] { 100, 250, 100, 400 };
		notificationManager.notify(R.string.app_name, notificacao);
	}
	
}
